from rest_framework import serializers
from .models import SystemMessage, MessageReadStatus
from authentication.models import Role


class SystemMessageSerializer(serializers.ModelSerializer):
    """
    系统消息序列化器
    """
    created_by_name = serializers.CharField(source='created_by.get_full_name', read_only=True)
    priority_display = serializers.CharField(source='get_priority_display', read_only=True)
    read_count = serializers.SerializerMethodField()
    is_expired = serializers.SerializerMethodField()
    
    class Meta:
        model = SystemMessage
        fields = [
            'id', 'title', 'content', 'priority', 'priority_display',
            'is_active', 'target_roles', 'target_companies',
            'created_by', 'created_by_name', 'created_at', 'updated_at',
            'expire_at', 'read_count', 'is_expired'
        ]
        read_only_fields = ['created_by', 'created_at', 'updated_at']
    
    def get_read_count(self, obj):
        """获取已读数量"""
        return obj.get_read_count()
    
    def get_is_expired(self, obj):
        """获取是否过期"""
        return obj.is_expired()
    
    def validate_target_roles(self, value):
        """验证目标角色"""
        if value:
            # 验证角色是否存在
            valid_roles = list(Role.objects.filter(name__in=value, is_active=True).values_list('name', flat=True))
            invalid_roles = [role for role in value if role not in valid_roles]
            if invalid_roles:
                raise serializers.ValidationError(f'以下角色不存在或未激活: {", ".join(invalid_roles)}')
        return value


class SystemMessageCreateSerializer(serializers.ModelSerializer):
    """
    创建系统消息的序列化器
    """
    class Meta:
        model = SystemMessage
        fields = [
            'title', 'content', 'priority', 'is_active',
            'target_roles', 'target_companies', 'expire_at'
        ]
    
    def validate_target_roles(self, value):
        """验证目标角色"""
        if value:
            valid_roles = list(Role.objects.filter(name__in=value, is_active=True).values_list('name', flat=True))
            invalid_roles = [role for role in value if role not in valid_roles]
            if invalid_roles:
                raise serializers.ValidationError(f'以下角色不存在或未激活: {", ".join(invalid_roles)}')
        return value


class MessageReadStatusSerializer(serializers.ModelSerializer):
    """
    消息阅读状态序列化器
    """
    message_title = serializers.CharField(source='message.title', read_only=True)
    user_email = serializers.CharField(source='user.email', read_only=True)
    
    class Meta:
        model = MessageReadStatus
        fields = ['id', 'message', 'message_title', 'user', 'user_email', 'read_at']
        read_only_fields = ['user', 'read_at']


class UserMessageSerializer(serializers.ModelSerializer):
    """
    用户消息序列化器 - 用于显示给普通用户的消息
    """
    priority_display = serializers.CharField(source='get_priority_display', read_only=True)
    is_read = serializers.SerializerMethodField()
    
    class Meta:
        model = SystemMessage
        fields = [
            'id', 'title', 'content', 'priority', 'priority_display',
            'created_at', 'expire_at', 'is_read'
        ]
    
    def get_is_read(self, obj):
        """获取当前用户是否已读该消息"""
        user = self.context['request'].user
        return MessageReadStatus.objects.filter(message=obj, user=user).exists()